package com.reggielcy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggielcy.common.R;
import com.reggielcy.dto.DishDto;
import com.reggielcy.entity.Category;
import com.reggielcy.entity.Dish;
import com.reggielcy.entity.DishFlavor;
import com.reggielcy.service.CategoryService;
import com.reggielcy.service.DishFlavorService;
import com.reggielcy.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @auther teacher
 * @date 2024/3/28
 * @project reggie_take_out
 */

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavors(dishDto);

        //清理redis中的相应分类的缓存
        Long categoryId = dishDto.getCategoryId();
        String key="dish_"+categoryId+"_1";
        redisTemplate.delete(key);

        return R.success("菜品信息保存成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapper);
        //根据categoryId查询category表的categoryName并赋值到dishDto对象中合成list返给前端
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");//records对应前端展示的数据

        List<Dish> lists = pageInfo.getRecords();

        List<DishDto> records=lists.stream().map((item)->{
            DishDto dishDto=new DishDto();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //属性拷贝
            BeanUtils.copyProperties(item,dishDto);
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());//合成list
        dishDtoPage.setRecords(records);


        return R.success(dishDtoPage);
    }
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavors(id);
        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //更新数据库
        dishService.updateWithFlavors(dishDto);

        //清理redis中的相应分类的缓存
        Long categoryId = dishDto.getCategoryId();
        String key="dish_"+categoryId+"_1";
        redisTemplate.delete(key);

        return R.success("菜品信息更改成功");
    }
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        Long categoryId = dish.getCategoryId();

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        queryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishList = dishService.list(queryWrapper);

        return R.success(dishList);
    }*/
    //功能延申到客户端
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList=null;

        Long categoryId = dish.getCategoryId();

        //优化: 先查询redis 获取dishDto
        String key="dish_"+categoryId+"_1";  //key:dish_1397844303408574465_1
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList!=null){
            //如果有值，则直接返回
            return R.success(dishDtoList);
        }

        //如果无值，则存入查询数据库后
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        queryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishList = dishService.list(queryWrapper);

        dishDtoList=dishList.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);

            //根据id查出口味
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());//合成list

        //缓存，redis中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }




}
